using System.Collections.Generic;
using MEC;
using UnityEngine;
using UnityEngine.UI;

namespace hatbox_hack
{
    public class ResistanceBar : MonoBehaviour
    {
        public Image FillBar;

        public GameObject gameObject;

        public static ResistanceBar CreateResistanceBar()
        {
            // 绑定
            GameObjects.hatboxHack.log("BIND");
            GameObject g = new GameObject();
            g.name = "ResistanceBar";
            ResistanceBar r = g.AddComponent<ResistanceBar>();
            r.gameObject = g;
            g.transform.position = new Vector3(0, 0, 0);
            g.SetActive(false);
            // Image
            GameObjects.hatboxHack.log("IMG");
            Canvas c = g.AddComponent<Canvas>();
            c.renderMode = RenderMode.ScreenSpaceOverlay;
            g.AddComponent<CanvasScaler>();
            g.AddComponent<GraphicRaycaster>();

            GameObjects.hatboxHack.log("FILLBAR");

            r.FillBar = g.AddComponent<Image>();

            Sprite white_64 = Resources.Load<Sprite>("Sprite/white_64");

            GameObjects.hatboxHack.log((white_64==null).ToString());

            r.FillBar.sprite = white_64;
            r.FillBar.color = Color.cyan;
            r.FillBar.type = Image.Type.Filled;
            r.FillBar.fillMethod = Image.FillMethod.Horizontal;
            r.FillBar.fillAmount = 0f;

            // back
            //g.SetActive(true);
            return r;
        }

        public void Init(Actor a)
        {
            FillBar.color = Color.blue;
            Timing.RunCoroutine(_Run(a).CancelWith(base.gameObject));
        }

        public IEnumerator<float> _Run(Actor a)
        {
            yield return 0f;
            int r = ActorExtras.I.resistance[a];
            while (
                r > 0
                && a.CurState != ActorState.kStunned
                && a.CurState != ActorState.kDead
                && a.isActiveAndEnabled
            )
            {
                r = ActorExtras.I.resistance[a];
                base.transform.position = a.transform.position + new Vector3(-0.4f, 0.25f, 0f);
                float fillAmount = r / Contract.I.EnemyResistanceLevel;
                FillBar.fillAmount = fillAmount;
                yield return 0f;
            }
            FXMgr_.I.RemoveResistanceBar(this);
        }
    }
}
